from rest_framework.serializers import ModelSerializer  # 序列化器
from .models import *  # 导入所有的模型类
from django.contrib.auth.models import User  # auth自带的用户表
from rest_framework import serializers

# 学生详情的序列化器
class UserDetailSerializer(ModelSerializer): # 序列化器类
    class Meta:
        model = UserDetail  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段
        # 数据校验 数值范围
        extra_kwargs = {
            "avatar": {"read_only": True},
            "user": {"required": False,'write_only':True},
        }

# 用户的序列化器
class UserSerializer(ModelSerializer): # 序列化器类
    # 嵌套详情表数据
    userdetail = UserDetailSerializer(required=False,read_only=True)

    class Meta:
        model = User  # 转序列化器
        exclude = ['password','last_name']  # 不想展示的字段

    # 数据校验 数值范围
    extra_kwargs = {
        "id":{"read_only":True},
        "last_login":{"read_only":True},
        "is_superuser":{"read_only":True},
        "is_staff":{"read_only":True},
        "is_active":{"read_only":True},
        "date_joined":{"read_only":True},
        "groups":{"read_only":True},
    }

class UpdatePasswordSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=60,label='原密码')
    new_password = serializers.CharField(max_length=60,label='新密码')
    re_new_password = serializers.CharField(max_length=60,label='确认新密码')

    # 对象级别校验
    def validate(self, data):  # data 字典
        if data['new_password'] != data['re_new_password']:
            raise serializers.ValidationError('两次密码输入不一致！')
        return data

# 查看所有省的序列化器
class AreaSerializer(ModelSerializer): # 序列化器类

    class Meta:
        model = Area  # 转序列化器
        fields = ['id','name']

# 省下面的市区
class ParentSerializer(ModelSerializer): # 序列化器类
    area_set = AreaSerializer(many=True,read_only=True)

    class Meta:
        model = Area  # 转序列化器
        fields = ['id','name','area_set']

import re
# 收货地址
class AddressSerializer(ModelSerializer): # 序列化器类
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_username = serializers.CharField(source='city.name', read_only=True)
    district_username = serializers.CharField(source='district.name', read_only=True)

    class Meta:
        model = Address  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段

    # 属性级别校验
    def validated_mobile(self, value):
        # 匹配开头
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机格式错误')
        return value



